/**
 * @file 故事主题
 * @module story/service/story
 * @author 月落 <yueluo.yang@qq.com>
 */

/**
 * @requires wx-server-sdk - 云函数库
 * @requires config/config - 链接配置
 */
const cloud = require('wx-server-sdk'),
      config = require('../config/config');

// 初始化云函数
cloud.init();
// 数据库实例
const db = cloud.database({
  env: config.env
});
// 数据库指令
const _ = db.command;

/**
 * @description 故事主题列表
 * @param {string} field - 主题
 * @param {string} page - 页码（可选）
 * @param {string} limit - 条数（可选）
 * @returns {object} 
 */
const topic = async ({ field, page = 1, limit = 10 }) => {
  const result = await db.collection(`${field}_stories`)
                         .skip((page - 1) * limit)
                         .limit(limit)
                         .field({
                          content: false
                         })
                         .get();

  if (result) {
    const { data } = result;

    return {
      code: 0,
      message: 'get topic list success.',
      data: {
        lists: data
      }
    }
  } else {
    return {
      code: -1,
      message: 'get topic list failed.',
      data: {}
    }
  }
}

/**
 * @description 故事主题详情列表
 * @param {string} id - 主题ID
 * @param {number} limit - 条数限制
 * @returns {object} 
 */
const list = async ({ field, id, limit = 50 }) => {
  const result = await db.collection(`${field}_stories`)
                         .limit(limit)
                         .where({
                           _id: id
                         })
                         .get();

  if (result) {
    const { data: [ { title, coverImgUrl, content } ] } = result;

    return {
      code: 0,
      message: 'get topic detail success.',
      data: {
        title,
        coverImgUrl,
        lists: content
      }
    }
  } else {
    return {
      code: -1,
      message: 'get topic detail failed.',
      data: {}
    }
  }
}

/**
 * @description 故事列表
 * @param {string} field - 主题
 * @param {string} page - 页码（可选）
 * @param {string} limit - 条数（可选）
 * @returns {object} 
 */
const story_list = async ({ field }) => {
  const result = await db.collection(`${field}_stories`)
                         .field({
                           title: false,
                           time: false,
                           coverImgUrl: false,
                           _id: false
                         })
                         .get();

  if (result) {
    let { data } = result;

    data = data.reduce((prev, item) => {
      const _content = item.content || [];
      return [...prev, ..._content];
    }, []);

    return {
      code: 0,
      message: 'get story list success.',
      data
    }
  } else {
    return {
      code: -1,
      message: 'get story list failed.',
      data: []
    }
  }
}

/**
 * @description 创建音频映射关系
 * @param {string} id - 故事ID
 * @param {string} url - 故事音频地址
 * @returns {object} 
 */
const create_audio = async ({ id, url }) => {
  await db.collection(`stories_audio_mapper`).add({
    data: { sid: id, url }
  });
  return {
    code: 0,
    message: 'insert audio data success.'
  }
}

/**
 * @description 查询音频地址
 * @param {string} id - 故事ID
 * @returns {object} 
 */
const get_audio = async ({ id }) => {
  const result = await db.collection(`stories_audio_mapper`)
                         .where({
                           sid: id
                         })
                         .get();

  if (result) {
    const { data: [ { url } ] } = result;

    return {
      code: 0,
      message: 'get audio url success.',
      data: {
        url
      }
    }
  } else {
    return {
      code: -1,
      message: 'get audio url failed.',
      data: {}
    }
  }
}

module.exports = {
  topic,
  list,
  story_list,
  create_audio,
  get_audio
}